package com.sh.caryr.erp.service.impl;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.mapper.Wrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import com.sh.caryr.erp.entity.enums.ProductTypeEnum;
import com.sh.caryr.erp.exception.ResultCode;
import com.sh.caryr.erp.entity.product.CombNum;
import com.sh.caryr.erp.entity.product.ProductSpec;
import com.sh.caryr.erp.entity.stock.Sku;
import com.sh.caryr.erp.exception.RestServiceException;
import com.sh.caryr.erp.mapper.ProductSpecMapper;
import com.sh.caryr.erp.service.ICombNumService;
import com.sh.caryr.erp.service.IProductSpecService;
import com.sh.caryr.erp.service.ISkuService;
import com.sh.caryr.erp.util.UtilityTool;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.Serializable;
import java.util.List;

/**
 * <p>
 * 商品规格表 服务实现类
 * </p>
 *
 * @author milkeeper
 * @since 2017-12-25
 */
@Service
public class ProductSpecServiceImpl extends ServiceImpl<ProductSpecMapper, ProductSpec> implements IProductSpecService {

    @Autowired
    private ISkuService skuService;

    @Autowired
    private ICombNumService combNumService;

    @Override
    public ProductSpec selectById(Serializable id){
        ProductSpec productSpec = super.selectById(id);
        if(productSpec!=null){
            this.getProductSpecDetail(productSpec);
        }
        return productSpec;
    }

    @Override
    public List<ProductSpec> findProductSpecsDynamic(Wrapper<ProductSpec> wrapper) {
        return this.findProductSpecsDynamic(wrapper, null, null, null);
    }

    @Override
    public List<ProductSpec> findProductSpecsDynamic(Wrapper<ProductSpec> wrapper, Integer size, Integer current, String orderBy) {
        List<ProductSpec> entityList;
        if (size != null) {
            wrapper.orderBy(orderBy);
            Page<ProductSpec> page = new Page<>(current, size);
            entityList = this.selectPage(page, wrapper).getRecords();
        } else {
            entityList = this.selectList(wrapper);
        }
        for (ProductSpec entity : entityList) {
            getProductSpecDetail(entity);
        }
        return entityList;
    }

    @Override
    public boolean insertProductSpecList(List<ProductSpec> productSpecList) {
        for (ProductSpec spec : productSpecList) {
            if (ProductTypeEnum.NORMAL == spec.getType()) {
                Sku sku = spec.getSku();
                if(sku!=null){
                    sku.setCoco(spec.getCoco());
                    sku.setProductId(spec.getProductId());
                    //==============Insert SKUs if they are new
                    if (skuService.insert(sku)) {
                        new RestServiceException(ResultCode.CREATE_FAILED);
                    }
                    spec.setSku(sku);
                    spec.setSkuId(sku.getId());
                }
                //==============Insert Product Spec
                if (!this.insert(spec)) {
                    new RestServiceException(ResultCode.CREATE_FAILED);
                }
            } else {
                //==============Insert Product Spec
                if (!this.insert(spec)) {
                    new RestServiceException(ResultCode.CREATE_FAILED);
                }
                //==============Insert combNum
                List<CombNum> combNumList = spec.getCombNumList();
                if (combNumList != null && !combNumList.isEmpty()) {
                    for (CombNum combNum : combNumList) {
                        combNum.setProductSpecId(spec.getId());
                        //TODO delete after data migration
                        combNum.setCombDetailId(spec.getId());
                    }
                    if (!combNumService.insertBatch(combNumList)) {
                        new RestServiceException(ResultCode.CREATE_FAILED);
                    }
                }
            }
        }
        return true;
    }

    @Override
    public boolean updateProductSpecList(List<ProductSpec> productSpecList){
        for (ProductSpec spec : productSpecList) {
            if (ProductTypeEnum.NORMAL == spec.getType()) {
                Sku sku = spec.getSku();
                if(sku!=null&&sku.getId()==null){
                    sku.setCoco(spec.getCoco());
                    sku.setProductId(spec.getProductId());
                    //==============Insert SKUs if they are new
                    if (skuService.insert(sku)) {
                        new RestServiceException(ResultCode.UPDATE_FAILED);
                    }
                    spec.setSku(sku);
                    spec.setSkuId(sku.getId());
                }
                //==============Insert or Update Product Spec
                if (!this.insertOrUpdateAllColumn(spec)) { //In order to handle the case skuId is set to null
                    new RestServiceException(ResultCode.UPDATE_FAILED);
                }
            } else {
                //==============Update Product Spec
                if (!this.insertOrUpdate(spec)) {
                    new RestServiceException(ResultCode.UPDATE_FAILED);
                }
                //==============Update combNum
                Wrapper combWrapper = new EntityWrapper<CombNum>().eq("productSpecId", spec.getId());
                List<CombNum> oldCombNumList = combNumService.selectList(combWrapper);
                List<CombNum> combNumList = spec.getCombNumList();
                if (combNumList != null && !combNumList.isEmpty()) {
                    for (CombNum combNum : combNumList) {
                        combNum.setProductSpecId(spec.getId());
                        //TODO delete after data migration
                        combNum.setCombDetailId(spec.getId());
                    }
                }
                try {
                    UtilityTool.insertUpdateDeleteEntities(CombNum.class, oldCombNumList, combNumList, combNumService);
                } catch (Exception e) {
                    e.printStackTrace();
                    new RestServiceException(ResultCode.UPDATE_FAILED);
                }
            }
        }
        return true;
    }

    private void getProductSpecDetail(ProductSpec entity){
        if(ProductTypeEnum.NORMAL.equals(entity.getType())) {
            if (entity.getSkuId() != null) {
                entity.setSku(skuService.selectById(entity.getSkuId()));
            }
        } else if (ProductTypeEnum.CONTAINSKU.equals(entity.getType())) {
            Wrapper combWrapper = new EntityWrapper<CombNum>().eq("productSpecId", entity.getId());
            entity.setCombNumList(combNumService.selectList(combWrapper));
        }
    }
}
